import {Directive, DirectiveBinding} from 'vue';
import hljs from 'highlight.js/lib/core';
import java from 'highlight.js/lib/languages/java'
import javascript from 'highlight.js/lib/languages/javascript'
import typescript from 'highlight.js/lib/languages/typescript'
import xml from 'highlight.js/lib/languages/xml'
import 'highlight.js/styles/atom-one-dark.css' //样式
import lineNumbersBlock from '@/utils/highlightjs-line-numbers.js'
import '@/styles/highlightjs-line-numbers.scss'

// 注册语言
hljs.registerLanguage('java', java)
hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('typescript', typescript)
hljs.registerLanguage('xml', xml)

import {marked} from "marked"; //样式
const rendererMD = new marked.Renderer();
marked.setOptions({
    renderer: rendererMD,
    gfm: true,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: true,
    smartypants: false,
    highlight: function (code) {
        return hljs.highlightAuto(code).value;
    }
});
/**
 * 高亮属性
 * <div v-highlight v-html="article" id="content"></div>
 *    this.article= marked(this.content);
 */
export const highlight: Directive = {
    updated(el: HTMLElement, binding: DirectiveBinding) {
        // // 查询选择器
        // let blocks = el.querySelectorAll('pre code');
        //
        // blocks.classList.add('hljs');
        // blocks.forEach((block: any) => {
        //     // hljs.highlightBlock(<HTMLElement>block)
        //     hljs.highlightBlock(block);
        //     hljs.lineNumbersBlock(block);
        // })
        // 查询需要渲染的代码
        let blocks = el.querySelectorAll('pre code');
        // 为 0 时渲染
        if (el.querySelectorAll('.hljs').length === 0) {
            blocks.forEach( (block:any) => {
                // 高亮
                hljs.highlightElement(block)
                lineNumbersBlock(block, {
                    singleLine: true
                });
            });
        }
    }
}

